package com.jstyle.jclife.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.jstyle.jclife.R;
import com.jstyle.jclife.activity.OtaActivity;
import com.jstyle.jclife.adapter.ScanDeviceAdapter;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.utils.ResolveData;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.SharedPreferenceUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link DeviceFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DeviceFragment extends DialogFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private static final String ARG_PARAM3 = "device";
    private static final String ARG_PARAM4= "deviceType";
    @BindView(R.id.listView_device)
    ListView listViewDevice;
    @BindView(R.id.bt_scan_device)
    Button btScanDevice;
    Handler mHandler=new Handler();
    ScanDeviceAdapter deviceAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private int mParam2;
    private BluetoothDevice device;
    private OnFragmentInteractionListener mListener;
    private boolean isScanning;

    public DeviceFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param
     * @return A new instance of fragment DeviceFragment.
     */
    // TODO: Rename and change types and number of parameters

    public static DeviceFragment newInstance(BluetoothDevice device, int rssi, String name) {
        DeviceFragment fragment = new DeviceFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, name);
        args.putInt(ARG_PARAM2,rssi);
        args.putParcelable(ARG_PARAM3,device);
//        args.putSerializable(ARG_PARAM4,jstyleDevice);
        fragment.setArguments(args);
        return fragment;
    }
  //  JstyleDevice jstyleDevice;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getInt(ARG_PARAM2);
            device=getArguments().getParcelable(ARG_PARAM3);
            //jstyleDevice= (JstyleDevice) getArguments().getSerializable(ARG_PARAM4);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);

        View view = inflater.inflate(R.layout.fragment_device, container, false);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        int width= ScreenUtils.getScreenWidth(getActivity())-ScreenUtils.dip2px(getActivity(),32);
        getDialog().getWindow().setLayout( width, ViewGroup.LayoutParams.WRAP_CONTENT);
        getDialog().setCancelable(false);
    }

    List<BluetoothDevice> deviceList =new ArrayList<>();
    private static final String TAG = "DeviceFragment";
    public void addDevice(BluetoothDevice device, int rssi, String name){
        if(deviceAdapter!=null&&isAdded()){
            deviceAdapter.addDevice(device,rssi,name);
        }
    }

    private void initView() {
        final BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();
        deviceAdapter=new ScanDeviceAdapter(getActivity(), deviceList);
     //   deviceAdapter.setDeviceDrawable(jstyleDevice.getDeviceListDrawableId());
        listViewDevice.setAdapter(deviceAdapter);
        deviceAdapter.addDevice(device,mParam2,mParam1);
        listViewDevice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice device=deviceAdapter.getItem(position);
                if(device==null)return;
                String deviceName=device.getName();
                if(TextUtils.isEmpty(deviceName))deviceName=deviceAdapter.getName(device);
                if(!TextUtils.isEmpty(device.getName())&&device.getName().toLowerCase().contains("dfu")){
                    dismiss();
                    startOta();
                    return;
                }
                if(mListener!=null&&device.getAddress()!=null){
                    BindDeviceInfo bindDeviceInfo=new BindDeviceInfo();
                    bindDeviceInfo.setConnected(true);
                    bindDeviceInfo.setDeviceName(deviceName);
                    bindDeviceInfo.setMacAddress(device.getAddress());
                    BindDeviceInfoDaoManager.insertData(bindDeviceInfo);
                    SharedPreferenceUtils.setSpString(SharedPreferenceUtils.KEY_deviceName,deviceAdapter.getName(device));
                    mListener.onFragmentInteraction(device.getAddress());
                }
                dismiss();
            }
        });
    }
    private String updateFileName="firmware.zip";
    private void startOta() {
        String path=SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_RES_FILEPATH);
        if(TextUtils.isEmpty(path))return;
        Intent intent = new Intent(getActivity(), OtaActivity.class);
        intent.putExtra(OtaActivity.EXTRA_FILE_PATH,  path+updateFileName);
        startActivity(intent);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {

        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        deviceAdapter.clear();
//        if(isScanning)
//        startScan(false);
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @OnClick(R.id.bt_scan_device)
    public void onClick() {

        dismiss();
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(String address);
    }
}
